from osgeo import ogr

def open_shapefile(path):
    """
    打开矢量文件  接受文件路径，返回一个layer
    """
    ds = ogr.Open(path, 0)  # 0是只读，1是可写
    layer = ds.GetLayer(0)          # 获取矢量文件Layer
    return layer



def write_shapefile(out_path, layer):
    """
    写出矢量文件
    """
    driver = ogr.GetDriverByName('ESRI Shapefile')
    ds_out = driver.CreateDataSource(out_path)
    layer_out = ds_out.CreateLayer('vector_new_2', geom_type=ogr.wkbPolygon, srs=layer.GetSpatialRef())
    fea_defn = layer_out.GetLayerDefn()    ## 获得空要素定义(或空图层定义)

    ### 创建字段
    layer_defn = layer_out.GetLayerDefn()
    print('Number of fields (before field creating): ', layer_defn.GetFieldCount())  ### 字段创建前字段数
    fea = layer.GetFeature(0)
    for i in range(fea.GetFieldCount()):
        field_defn = fea.GetFieldDefnRef(i)
        layer_out.CreateField(field_defn)
    layer_defn = layer_out.GetLayerDefn()
    print('Number of fields (after field creating): ', layer_defn.GetFieldCount())

    for fea in layer:
        fea_out = ogr.Feature(fea_defn)
        fea_out.SetGeometry(fea.geometry())
        for i in range(fea.GetFieldCount()):
            field_value = fea.GetField(i)
            fea_out.SetField(i, field_value)
        layer_out.CreateFeature(fea_out)
    ds_out = None        #  ### 保存/关闭 DataSource
    print("done")




def show_fields(layer):
    """
    显示字段
    """
    fields = []
    fea = layer.GetFeature(0)
    num_field = layer.GetFeature(0).GetFieldCount() 
    for i in range(0, num_field):
        field = fea.GetFieldDefnRef(i).name
        fields.append(field)
    print(fields)



    